package com.biubiux2.async;

import com.biubiux2.cache.UserDataCache;
import com.biubiux2.dao.DaoUtil;
import com.biubiux2.dao.UserDataMapper;
import com.biubiux2.entity.UserData;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author noexcs
 * @since 8/12/2022 9:40 PM
 */
public class GamerThread extends Thread {

    public static final GamerThread[] THREADS = new GamerThread[8];

    public ConcurrentHashMap<Integer, UserDataCache> userDataCacheHashMap = new ConcurrentHashMap<>();

    static {
        for (int i = 0; i < THREADS.length; i++) {
            THREADS[i] = new GamerThread();
        }
    }

    public final LinkedBlockingQueue<Runnable> tasks = new LinkedBlockingQueue<>();

    public static void submit(Runnable runnable, int uid) {
        THREADS[uid & (THREADS.length - 1)].tasks.add(runnable);
    }

    public GamerThread() {
        start();
    }

    @Override
    public void run() {
        while (true) {
            try {
                Runnable runnable = tasks.take();
                runnable.run();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public UserDataCache getUserDataCache(int uid) {
        UserDataCache cache = userDataCacheHashMap.get(uid);
        if (cache != null) {
            return cache;
        }
        UserDataMapper mapper = DaoUtil.getMapper(UserDataMapper.class);
        UserData userData = mapper.getUserData(uid);
        cache = new UserDataCache();
        cache.setUserData(userData);
        userDataCacheHashMap.put(uid, cache);
        return cache;
    }

    public static GamerThread getUserAttachedThread(int uid) {
        return THREADS[uid % THREADS.length];
    }
}
